package com.crazymaker.agent.demo.javassist;

import java.lang.instrument.Instrumentation;
import java.lang.instrument.UnmodifiableClassException;

public class TransformerAgentDemo {

    //jvm 参数启动，运行此方法
    public static void premain(String args, Instrumentation instrumentation) {

        System.out.println("premain:" + args);
        // 对字节码进行增强转换
        instrumentation.addTransformer(new Transformer(), true);
        try {
            assistClass(args, instrumentation);
        } catch (UnmodifiableClassException e) {
            e.printStackTrace();
        }
    }


    private static void assistClass(String args, Instrumentation inst) throws UnmodifiableClassException {
        Class[] clazzes = inst.getAllLoadedClasses();
        for (int i = 0; i < clazzes.length; i++) {
            if (clazzes[i].getName().contains("Helloworld")) {
                log("重新加载：" + clazzes[i].getName());
                inst.retransformClasses(clazzes[i]);
            }
        }
    }


    private static void log(String s) {

        System.out.println("TransformerAgentDemo:" + s);

    }


    //动态 attach 方式启动，执行此方法

    public static void agentmain(String args, Instrumentation inst) {
        System.out.println("agentmain:" + args);
        inst.addTransformer(new Transformer(), true);
        try {
            assistClass(args, inst);
        } catch (UnmodifiableClassException e) {
            e.printStackTrace();
        }
    }
}